<?php

/**
 * 更新wiki点击购买的数量
 * 每天凌晨6点10跑
 *
 **/


ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

//查询数据组数据库，更新wiki表click_buy_num字段

use Biz\model\bigData\WikiBuyNum as mWikiBuyNum;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiBasic;
use Doraemon\pockets\config\IniConfig;
use Doraemon\tools\Log;
use Doraemon\tools\Presto\PrestoClientV2;
use Doraemon\tools\Presto\PrestoException;

//更新商品热度
SyncBasicGoodsHot();

//更新品牌指数
syncBrandScore();

$page = 1;
$pageSize = 3000;
$list = [];
do {
    $limit = [($page - 1) * $pageSize, $pageSize];
    $list = mWikiBuyNum::select('*', ['LIMIT' => $limit]);
    var_dump('查询' . $page * $pageSize . '条');
    $wikiIds = array_column($list, 'wiki_id');
    foreach ($list as $row) {
        mWiki::update(['click_buy_num' => $row['click_buy_num']], ['id' => $row['wiki_id'], 'click_buy_num[!]' => $row['click_buy_num']]);
    }
    var_dump('提前查询联盟转链#page:' . $page);
    createUnionUrl($wikiIds);
    $page++;
} while ($list);

function createUnionUrl($wikiIds)
{
    $wikiIds = array_unique($wikiIds);
    $wikiList = mWiki::selectByWhere(['id' => $wikiIds], ['id', 'channel', 'channel_spu_id', 'channel_jump_params']);
    $tbItemIdsArr = [];
    $jdItemIds = [];
    foreach ($wikiList as $row) {
        switch ($row['channel']) {
            case mWiki::CHANNEL_TAOBAO:
                $tbItemIdsArr[$row['channel_spu_id']] = $row['channel_jump_params'];
                break;
            case mWiki::CHANNEL_JD:
                $jdItemIds[] = $row['channel_spu_id'];
                break;
        }
    }
    \Biz\module\Classes\wiki\Wiki::_async_createUnionUrl($tbItemIdsArr, $jdItemIds);
}

//同步商品热度数据到redis以及store.wiki.basic_goods_hot
function SyncBasicGoodsHot()
{
    //数据是每天3点前跑完数据 定时任务目前是6点取数据
    $basicIdMax = WikiBasic::get('id', ['LIMIT' => 1, 'ORDER' => ['id' => 'DESC']]);
    $pageSize = 5000;

    $page = ceil($basicIdMax / $pageSize);
    // 初始化presto客户端
    $config = IniConfig::getConfigSelect('presto', 'brand');
    $presto = new PrestoClientV2("{$config['host']}:{$config['port']}/{$config['path']}", "hive", $config["username"],
        $config["password"]);
    $i = 0;
    try {
        while ($i < $page) {
            try {
                $start = $i * $pageSize;
                $end = ($i + 1) * $pageSize;
                $presto->Query("select id,wiki_score as score from oss.hhz.dwd_brand_wiki_score  where id >{$start} and  id<= {$end}");
                $presto->WaitQueryExec();
            } catch (PrestoException $e) {
                Log::error('同步商品热度数据异常'.$e);
            }
            $data = $presto->GetData();
            echo '这是第'.($i + 1).'批数据处理开始,共：'.(count($data)).'条数据'.PHP_EOL;
            Log::info('这是第'.($i + 1).'批数据处理开始,共：'.(count($data)).'条数据');
            if ($data) {
                foreach ($data as $row) {
                    //更新商品热度缓存
                    \Biz\cache\wiki\GoodsHot::setGoodsHotById($row[0],$row[1]);
                    //更新数据库 store.wiki.basic_goods_hot
                    mWiki::update(['basic_goods_hot' => $row[1]], ['basic_id' => $row[0], 'basic_goods_hot[!]' => $row[1]]);
                }
            }
            echo '这是第'.($i + 1).'批数据处理结束,共：'.(count($data)).'条数据被处理'.PHP_EOL;
            Log::info('这是第'.($i + 1).'批数据处理结束,共：'.(count($data)).'条数据被处理');
            $i++;
        }
    } catch (Exception $exception) {
        Log::info('同步商品热度数据异常', ['exception' => $exception]);
    }
}

//更新品牌指数
function syncBrandScore()
{
    $data = \Biz\model\brand\Brand::select('id',['id[>]'=>0]);
    if($data){
        foreach ($data as $brandId){
            $score = \Biz\cache\brand\BrandScoreCache::getBrandScore($brandId);
            \Biz\model\brand\Brand::update(['brand_score' => $score], ['id' => $brandId, 'brand_score[!]' => $score]);
        }
    }
}




